import React from 'react';
import { Icon, Row, Input, Select } from 'antd';
import classNames from 'classnames';
import { WeaCheckbox, WeaInput, WeaLocaleProvider } from 'ecCom';
import { ruleTypes } from '../../../../constants/form';
import { CHECKED, UNCHECKED } from '../../../../constants/common';

const { FIELD, JUMP } = ruleTypes;
const { getLabel } = WeaLocaleProvider;
const formatMultiLang = WeaLocaleProvider.formatMultiLang;

const Item = ({ active, onClick, children }) => (
  <li
    className={classNames({ active })}
    onClick={onClick}
    style={{ overflow: 'hidden', 'text-overflow': 'ellipsis', 'white-space': 'nowrap' }}
    title={children}
  >
    {children}
  </li>
);

const List = ({ data = [], onClick, active, text }) => (
  <ul>
    {data.map((item,index) => (
      <Item ecId={`${this && this.props && this.props.ecId || ''}_Item@yeo7l6@${index}`}
        active={active(item)}
        onClick={() => onClick(item)}
      >
        {formatMultiLang(text(item))}
      </Item>
    ))}
  </ul>
);

export default class RuleSettings extends React.Component {
  static defaultProps = {
    rule: null, // 规则
    triggers: [], // 触发规则的插件
    targets: [], // 可以使用规则的插件
    onChange: () => { }, // 规则change回调
  };

  constructor(props) {
    super();

    const {
      trigger = {},
    } = props.rule || {};

    this.state = {
      targets: this.getTargets(props.targets, trigger),
    };
  }

  componentWillReceiveProps(nextProps) {
    if (!nextProps.rule) return;

    const { trigger } = nextProps.rule;

    this.setState({
      targets: this.getTargets(nextProps.targets, trigger),
    });
  }

  onTriggerChange = (trigger) => {
    const { targets, onChange, rule } = this.props;
    const newTargets = this.getTargets(targets, trigger);
    let newTarget = rule.target;

    if (FIELD === rule.type) {
      newTarget = rule.target.filter(t => newTargets.find(nt => t.id === nt.id));

      this.setState({
        targets: this.getTargets(targets, trigger),
      });
    }

    onChange({
      trigger,
      option: { key: '', showname: '' },
      target: newTarget,
    });
  }

  getTargets(targets, trigger) {
    const index = targets.findIndex(t => trigger.id === t.id);

    return targets.slice(index + 1);
  }

  onOptionChange = (option) => {
    this.props.onChange({ option });
  }

  onTargetChange = (target, isChecked) => {
    const { rule, onChange } = this.props;

    if (JUMP === rule.type) {
      return onChange({ target });
    }
    const t = [...rule.target];

    if (!isChecked) {
      const index = t.findIndex(t => t.id === target.id);

      t.splice(index, 1);
    } else {
      t.push(target);
    }

    onChange({ target: t });
  }

  getJumpRuleVals = (target) => {
    let selectVal = '';
    let value = target;

    // 判断是否符合以下两种类型或者是新增
    if (~target.indexOf('http://')) {
      selectVal = 'http://';
      value = target.split('http://')[1];
    } else if (~target.indexOf('https://')) {
      selectVal = 'https://';
      value = target.split('https://')[1];
    } else if (target === '') {
      selectVal = 'http://';
    }

    const options = (
      <Select ecId={`${this && this.props && this.props.ecId || ''}_Select@jk0y2o`} value={selectVal} className="url-before-select" onSelect={value => this.onUrlBeforeSelect(value)}>
        <Option ecId={`${this && this.props && this.props.ecId || ''}_Option@fuw4wn`} value="http://" className="url-select">http://</Option>
        <Option ecId={`${this && this.props && this.props.ecId || ''}_Option@uk9rqf`} value="https://" className="url-select">https://</Option>
      </Select>);

    return {
      options,
      selectVal,
      value,
    };
  }

  onUrlBeforeSelect = (value) => {
    const { targets } = this.state;
    let { rule: { type, target } } = this.props;

    if (value === 'http://' && !!~target.indexOf('https://')) {
      target = value + target.split('https://')[1];
    } else if (value === 'https://' && !!~target.indexOf('http://')) {
      target = value + target.split('http://')[1];
    } else {
      target = value + target;
    }

    this.onTargetChange(target);
  }

  renderRuleAction() {
    const { targets } = this.state;
    const { rule: { type, target } } = this.props;
    const style = { marginBottom: 5 };

    if (FIELD === type) {
      return (
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@9yyxab`}>
          <p style={style}>{getLabel(503923, '就显示以下字段')}</p>
          {targets.map((t,i) => (
            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@p7ndjc@${i}`}
              style={{ display: 'block' }}
              value={target.find(ts => t.id === ts.id) ? CHECKED : UNCHECKED}
              content={t.name}
              onChange={v => this.onTargetChange(t, v === CHECKED)}
            />
          ))}
        </Row>
      );
    } else if (JUMP === type) {
      const {
        options,
        value,
        selectVal,
      } = this.getJumpRuleVals(target);

      return (
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@t1wa8i`}>
          <p style={style}>{getLabel(503924, '就跳转到')}:</p>
          <Input ecId={`${this && this.props && this.props.ecId || ''}_Input@0sg0yu`}
            addonBefore={options}
            placeholder={`${getLabel(83103, '如')}: www.xxx.com`}
            value={value}
            onChange={e => this.onTargetChange(selectVal + e.target.value)}
          />
        </Row>
      );
    }
  }

  render() {
    const { rule, triggers } = this.props;

    if (!rule) return null;

    const { trigger, option } = rule;

    return (
      <div className="rule-settings-container">
        <h4><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@7pjehg`} type="settings" />{getLabel(503925, '设置规则')}</h4>
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@wg2aqd`}>
          <p style={{ margin: '5px 0' }}>{getLabel(503926, '如果')}:</p>
          {getLabel(503928, '在______中')}
          <List ecId={`${this && this.props && this.props.ecId || ''}_List@s0rj9y`}
            data={triggers}
            active={({ id }) => trigger.id === id}
            text={({ name }) => name}
            onClick={this.onTriggerChange}
          />
        </Row>
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@cv0cag`}>
          {getLabel(503929, '选择了')}______
          <List ecId={`${this && this.props && this.props.ecId || ''}_List@c90bvw`}
            data={trigger.options}
            active={({ key }) => option.key === key}
            text={({ showname }) => showname}
            onClick={this.onOptionChange}
          />
        </Row>
        {this.renderRuleAction()}
      </div>
    );
  }
}
